<-- 用法：
1、安装
  npm install -S file-saver xlsx
  npm install -D script-loader
2、调用
import importExcel from '@/views/app/biz/common/importExcel'
import exportExcel from '@/views/app/biz/common/exportExcel/index.vue' 
 //exportExcel相当于一个按钮
<export-excel ref="export" @getExcelData="onExportData"></export-excel>

//method里
  onExportData(){
    //如需请求数据，则在此请求数据后执行以下
    let listName="基础商品信息"
    let listHeader=['商品自编码','商品名称','一级分类（学科、品类）','二级分类（用途、品目）','三级分类（部位、功能、品种）','品牌']
    let listField=['code','productNameZh','first','second','third','brand']
    let exportList=this.listdata
    this.$refs.export.setData(listName,listHeader,listField,exportList)
  }
-->

<template>
  <a-button :type="btnType" :size="size" @click="onExport" icon="vertical-align-bottom"> {{btnText}} </a-button>
</template>

<script>
import moment from 'moment'
export default {
  props:{
    btnText:{
      type:String,
      default:'导出数据'
    },
    btnType:{
      type:String,
      default:'primary'
    },
    size:{
      type:String,
      default:null
    }
  },
  data(){
    return{
      //excel表格名称
      listName:'数据',
      //excel表格表头
      listHeader:['编码', '名称', '价格'],
      //excel表格表头对应数据的字段
      listField:['code', 'name', 'price'],
      //excel表格数据
      exportList:[
        { code: '832713123213123123123', name: '手表', price: '67' },
        { code: '8324123', name: '尺子', price: '17' },
        { code: '8357123213123', name: '项链', price: '287' }
      ]

    }
  },
  methods: {
    //点击导出请求数据，则在父组件监听此函数
    onExport() {
      this.$emit('getExcelData')
    },
    //父组件请求数据后调用此函数传配置数据
    setData(listName,listHeader,listField,exportList){
      this.listName=listName,
      this.listHeader=listHeader,
      this.listField=listField,
      this.exportList=exportList
      this.export2Excel()
    },
    export2Excel() {
      require.ensure([], () => {
        const { export_json_to_excel } = require('./Export2Excel')
        //导出时间
        let optTime= moment(new Date).format("YYYYMMDDhhmmss")
        const listName = this.listName+'_'+optTime
        const listHeader = this.listHeader
        const listField = this.listField
        const list = this.exportList
        const data = this.formatJson(listField, list)
        export_json_to_excel(listHeader, data, listName)
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    }
  }
}
</script>

<style>
</style>
